<template>
	<div class="groupcContainer">
		<div v-if="canAdd" class="btn_basenav">
			<el-button type="primary" size="mini" @click="show_add_groups = true;is_add = true">新增</el-button>
		</div>
		<div class="tableContainer">
			<el-table :data="searchs(search)" v-loading="loading" style="width: 100%" max-height="500">
				<el-table-column sortable prop="pk" label="ID"></el-table-column>
				<el-table-column sortable prop="name" label="分组名称"></el-table-column>
				<el-table-column prop="permissions" label="分组权限">
					<template slot-scope="scope">
						<el-popover placement="left" width="400" trigger="hover">
							<el-table :data="scope.row.permissions" max-height="500">
								<el-table-column sortable width="70" property="id" label="ID"></el-table-column>
								<el-table-column property="name" label="权限名"></el-table-column>
								<el-table-column property="codename" label="权限代码"></el-table-column>
							</el-table>
							<el-button size="small" type="success" slot="reference">查看所属权限</el-button>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column>
					<template slot="header" slot-scope="scope">
						<div style="display:flex;">
							<span style="dispaly:none">{{scope.row}}</span>
							<el-input v-model="search" size="mini" placeholder="输入菜单名搜索" />
						</div>
					</template>
					<template slot-scope="scope">
						<el-button
							v-if="canEdit"
							type="primary"
							size="mini"
							@click="handleEdit(scope.$index, scope.row)"
						>编辑</el-button>
						<el-popover v-if="canRemove" placement="top" width="160" v-model="scope.row.color">
							<p>确定删除吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="scope.row.color = false">取消</el-button>
								<el-button type="primary" size="mini" @click="remove_group(scope.row,scope.$index)">确定</el-button>
							</div>
							<el-button slot="reference" size="mini" type="danger">删除</el-button>
						</el-popover>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 新增&&编辑 主菜单弹框 -->
		<el-dialog
			title="分组操作"
			:before-close="handleClose"
			:visible.sync="show_add_groups"
			width="38%"
			center
		>
			<el-form
				:model="group_form"
				status-icon
				:rules="rules_group"
				ref="show_add_group"
				label-width="80px"
				class="demo-ruleForm"
			>
				<el-form-item label="组名" prop="name">
					<el-input type="text" v-model="group_form.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="权限" prop="per">
					<el-select
						v-model="group_form.per"
						suffix-icon="el-icon-date"
						filterable
						multiple
						placeholder="请选择"
					>
						<el-option v-for="item in per_list" :key="item.value" :label="item.label" :value="item.value">
							<span style="float: left">
								{{item.label}}
							</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.codename }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<div class="btns">
						<el-button size="small" type="success" @click="save_group('show_add_group')">保存</el-button>
						<!-- <el-button size="small" type="danger" @click="resetForm('ruleForm')">重置</el-button> -->
					</div>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>


<script>
export default {
	data() {
		var validatename = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请输入分组名"));
			} else {
				if (value.length > 8) {
					callback(new Error("分组名不能超过8个字符"));
				} else {
					callback();
				}
			}
		};
		var validateper = (rule, value, callback) => {
			callback();
		};
		return {
			canAdd: false,
			canRemove: false,
			canEdit: false,
            loading: false,
            is_add:false,
            show_add_groups: false,
            select_id:null,
			group_list: [],
			per_list: [],
			user_infos: {},
			search: "",
			group_form: {
				name: "",
				per: []
			},
			rules_group: {
				name: [
					{
						validator: validatename,
						trigger: "blur"
					}
				],
				per: [
					{
						validator: validateper,
						trigger: "blur"
					}
				]
			}
		};
	},
	methods: {
		// 搜索功能
		searchs(kw) {
			let searchingList = [];
			this.group_list.forEach(item => {
				if (item.name.indexOf(kw) != -1) {
					searchingList.push(item);
				}
			});
			return searchingList;
		},
		// 获取分组列表
		get_group_list() {
			this.$ajax
				.get("/groups")
				.then(res => {
					this.group_list = res.data;
					let that = this;
					setTimeout(function() {
						that.loading = false;
					}, 200);
				})
				.catch(err => {
					this.$message({
						message: "网络错误！",
						type: "info"
					});
					let that = this;
					setTimeout(function() {
						that.loading = false;
					}, 200);
				});
		},
		// 获取权限列表
		get_permissions() {
			this.$ajax.get("/permissions").then(res => {
                res.data.forEach(item=>{
                    let obj = {value:item.id,label:item.name,codename:item.codename}
                    this.per_list.push(obj);
                })
				
			});
		},
		// 新增分组
		confirm_add_group(flag) {
            if(flag == 'add'){
                let form = new FormData()
                form.append('name',this.group_form.name)
                if(this.group_form.per.length>0){
                    this.group_form.per.forEach(item=>{
                        form.append('permissions',item)
                    })
                }
                this.$ajax.post('/groups/',form).then(res=>{
                    console.log(res.data)
                    this.$message({
                        message:"操作成功!",
                        type:"success"
                    });
                    this.get_group_list();
                    this.show_add_groups = false;
                }).catch(err=>{
                    this.$message({
                        message:"网络错误!",
                        type:"warning"
                    });
                })
            }else{
                let form = new FormData()
                form.append('name',this.group_form.name)
                if(this.group_form.per.length>0){
                    this.group_form.per.forEach(item=>{
                        form.append('permissions',item)
                    })
                };
                this.$ajax.put('/groups/' + this.select_id + '/',form).then(res=>{
                    this.$message({
                        message:"操作成功!",
                        type:"success"
                    });
                    this.get_group_list();
                    this.show_add_groups = false;
                }).catch(err=>{
                    this.$message({
                        message:"网络错误!",
                        type:"warning"
                    });
                })
            }
		},
		// 确认新增分组
		save_group(formName) {
            this.$refs[formName].validate(valid => {
				if (valid) {
                    if(this.is_add){
                        this.confirm_add_group('add');
                    }else{
                        this.confirm_add_group('edit');
                    }
				} else {
					return false;
				}
			});
        },
		// 编辑分组
		handleEdit(index, item) {
            this.show_add_groups = true;
            this.select_id = item.pk
            this.group_form.name = item.name;
            item.permissions.forEach(items=>{
                this.group_form.per.push(items.id)
            });
        },
		// 删除分组
		remove_group(item, index) {
            this.$ajax.delete("/groups/" + item.pk + '/').then(res=>{
                this.$message({
                        message:"操作成功!",
                        type:"success"
                    });
                this.group_list.splice(index,1);
            }).catch(err=>{
                this.$message({
                        message:"网络错误!",
                        type:"warning"
                    });
            })
        },
		handleClose(done) {
			this.$confirm("确认关闭？")
				.then(_ => {
					// this.resetForm("ruleForm");
					done();
				})
				.catch(_ => {});
		}
	},
	created() {
		this.loading = true;
		this.get_group_list();
		this.get_permissions();
	},
	mounted() {
		this.user_infos = JSON.parse(window.localStorage.getItem("user"));
		if (this.user_infos.user_permissions.length > 0) {
			this.user_infos.user_permissions.forEach(item => {
				if (item.codename == "add_group") {
					this.canAdd = true;
					return false;
				}
			});
			this.user_infos.user_permissions.forEach(item => {
				if (item.codename == "change_group") {
					this.canEdit = true;
					return false;
				}
			});
			this.user_infos.user_permissions.forEach(item => {
				if (item.codename == "delete_group") {
					this.canRemove = true;
					return false;
				}
			});
		}
	}
};
</script>


<style lang="scss" scoped>
.el-select {
	width: 100%;
}
</style>